from django.db import models
from django.core.validators import MinLengthValidator, RegexValidator
from django.core.exceptions import ValidationError
import re
from django.contrib.auth.hashers import make_password, check_password

class Shop(models.Model):
    name = models.CharField("店铺名称", max_length=100, unique=True)

    SHOP_TYPE_CHOICES = [
        ('normal', '普通店铺'),
        ('flagship', '旗舰店'),
        ('franchise', '专营店'),
        ('exclusive', '专卖店'),
    ]

    shop_type = models.CharField(
        max_length=20,
        choices=SHOP_TYPE_CHOICES,
        default='normal',
        verbose_name="店铺类型"
    )
    is_cross_border = models.BooleanField(
        default=False,
        verbose_name="是否跨境"
    )

    invite_code = models.CharField(
        max_length=225,  # 需要增加长度以存储哈希值
        blank=True,
        null=True,
        verbose_name="店铺邀请码"
    )

    def save(self, *args, **kwargs):
        # 如果邀请码不为空且没有被哈希过
        if self.invite_code and not self.invite_code.startswith('pbkdf2_sha256'):
            self.invite_code = make_password(self.invite_code)
        super().save(*args, **kwargs)

    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )

    class Meta:
        verbose_name = "店铺"
        verbose_name_plural = "店铺"

    def __str__(self):
        return self.name


# 修改UserData模型
class UserData(models.Model):
    # 商户ID - 保持不变
    merchant_id = models.IntegerField(
        unique=True,
        verbose_name="商户ID",
        editable=False
    )

    # 账号信息
    username = models.CharField(
        max_length=50,
        unique=True,
        verbose_name="用户名",
        validators=[
            MinLengthValidator(3, message="用户名至少需要3个字符")
        ]
    )
    password = models.CharField(
        max_length=128,
        verbose_name="密码",
        validators=[
            MinLengthValidator(8, message="密码至少需要8个字符")
        ]
    )

    # 关联到Shop模型, 一个店铺可以有多个用户
    shop = models.ForeignKey(
        Shop,
        on_delete=models.CASCADE,
        related_name='users',
        verbose_name="所属店铺"
    )

    # 添加省份字段
    province = models.CharField(
        max_length=50,
        verbose_name="所在省份",
        blank=True,
        null=True
    )
    # 联系信息
    email = models.EmailField(
        max_length=100,
        unique=True,
        verbose_name="电子邮箱"
    )
    phone = models.CharField(
        max_length=11,
        unique=True,
        verbose_name="手机号码",
        validators=[
            RegexValidator(
                regex=r'^\d{11}$',
                message="请输入11位数字的手机号码"
            )
        ]
    )

    # 系统信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )

    class Meta:
        verbose_name = "用户数据"
        verbose_name_plural = "用户数据"
        ordering = ['-created_at']

    def clean(self):
        # 自定义验证逻辑
        if not re.match(r'^[\w]+@[A-Za-z]+(\.[A-Za-z0-9]+){1,2}$', self.email):
            raise ValidationError({'email': "邮箱格式不正确"})

        if not self.phone.isdigit() or len(self.phone) != 11:
            raise ValidationError({'phone': "电话号码必须为11位数字"})

    def save(self, *args, **kwargs):
        if not self.merchant_id:
            max_id = UserData.objects.aggregate(
                models.Max('merchant_id')
            )['merchant_id__max'] or 1000
            self.merchant_id = max_id + 1
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.username} - {self.shop.name}"


from django.db import models
from django.utils import timezone


class Product(models.Model):
    # 从关联用户改为关联店铺
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='products')

    SPEC_CHOICES = [
        ('L', '大'),
        ('M', '中'),
        ('S', '小')
    ]

    name = models.CharField("商品名称", max_length=100)
    code = models.CharField("编号", max_length=20)
    spec = models.CharField("规格", max_length=1, choices=SPEC_CHOICES)
    cost = models.DecimalField("进价/件", max_digits=10, decimal_places=2)
    price = models.DecimalField("售价/件", max_digits=10, decimal_places=2)
    stock = models.IntegerField("库存数量", default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        # 修改联合唯一约束，确保每个店铺的产品编号唯一
        unique_together = ['shop', 'code']




# 在 models.py 中
class InventoryOperation(models.Model):
    OPERATION_CHOICES = [
        ('IN', '入库'),
        ('OUT', '出库'),
        ('NEW', '新建商品'),
        ('DEL', '删除商品')  # 确保有删除商品的操作类型
    ]

    product = models.ForeignKey(
        Product,
        on_delete=models.SET_NULL,
        related_name='operations',
        null=True  # 允许为空
    )
    # 增加商品编号字段，用于记录被删除的商品编号
    product_code = models.CharField("商品编号", max_length=20, blank=True)
    product_name = models.CharField("商品名称", max_length=100, blank=True)
    operation_type = models.CharField("操作类型", max_length=3, choices=OPERATION_CHOICES)
    quantity = models.IntegerField("数量")
    note = models.TextField("备注", blank=True)
    operator = models.CharField("操作人", max_length=50, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-timestamp']


# 添加到models.py文件中
# 添加到models.py文件中
from django.db import models
from django.utils import timezone

# 普通商单模型
class NormalOrder(models.Model):
    # 关联到店铺而不是用户
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='normal_orders')
    # 添加创建者字段，记录谁创建了这个订单
    creator = models.ForeignKey(UserData, on_delete=models.SET_NULL, null=True, related_name='created_normal_orders')

    order_id = models.CharField("订单编号", max_length=20, unique=True)
    customer = models.CharField("客户", max_length=100)
    product = models.CharField("商品", max_length=100)
    quantity = models.IntegerField("数量")
    amount = models.DecimalField("金额", max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = "普通商单"
        verbose_name_plural = "普通商单"

    def __str__(self):
        return f"{self.order_id} - {self.customer} - {self.product}"

# 隐私商单模型
class PrivateOrder(models.Model):
    # 关联到店铺而不是用户
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='private_orders')
    # 添加创建者字段
    creator = models.ForeignKey(UserData, on_delete=models.SET_NULL, null=True, related_name='created_private_orders')

    order_id = models.CharField("订单编号", max_length=20, unique=True)
    customer = models.CharField("客户", max_length=100)
    product = models.CharField("商品", max_length=100)
    quantity = models.IntegerField("数量")
    amount = models.DecimalField("金额", max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = "隐私商单"
        verbose_name_plural = "隐私商单"

    def __str__(self):
        return f"{self.order_id} - {self.customer} - {self.product}"